# 绘制我方炮筒
import pygame
from setting import *


class MyGun(pygame.sprite.Sprite):
    def __init__(self) -> None:
        super().__init__()
        # 己方炮筒每一帧的动画
        self.img_list = [
            pygame.image.load(r'img/gun/gun_01.png').convert_alpha(),
            pygame.image.load(r'img/gun/gun_02.png').convert_alpha(),
            pygame.image.load(r'img/gun/gun_03.png').convert_alpha(),
            pygame.image.load(r'img/gun/gun_04.png').convert_alpha()
        ]
        # 每一帧图片替换的索引，表示当前帧
        self.my_gun_img_index = 0
        # 被绘制的图片
        self.image = self.img_list[0]
        self.img_rect_center = self.image.get_rect(center=(350, HEIGHT - 80))
        self.img_rect = self.img_rect_center
        # 默认存活
        self.active = True
        # 初始化枪的角度为0
        self.angle = 0
        # 得分
        self.score = 0
        # 击杀魔鬼鱼和鲨鱼的数量
        self.kill_manta = 0
        self.kill_shark = 0

    def update(self, keys, delay):
        """
        更新大炮，不管是否旋转，都要替换每一帧的图片，达到动态的效果
        先将图片索引+1指向下一帧，然后将源图替换为下一帧
        被绘制的图片根据源图进行旋转，如果用户输入方向键，则还需要增加旋转角度
        """
        if delay % 10 == 0:
            self.add_img_index()
            self.image = self.img_list[self.my_gun_img_index]
        """ 根据左右键位进行操作 """
        if keys[pygame.K_LEFT] or keys[pygame.K_a]:
            self.move_left()
        elif keys[pygame.K_RIGHT] or keys[pygame.K_d]:
            self.move_right()

    def move_left(self):
        """ 控制炮向左移动 """
        if self.img_rect.left - GUN_SPEED <= 10:
            return
        self.img_rect.left -= GUN_SPEED

    def move_right(self):
        """ 控制炮向右移动 """
        if self.img_rect.left + self.img_rect.width + GUN_SPEED >= WIDTH - 10:
            return
        self.img_rect.left += GUN_SPEED

    def add_img_index(self):
        self.my_gun_img_index = (self.my_gun_img_index + 1) % len(self.img_list)
